#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
LOG_DIR="${ROOT_DIR}/logs"
PID_FILE="${ROOT_DIR}/uvicorn.pid"
LOG_FILE="${LOG_DIR}/uvicorn.log"
RSSHUB_DIR="${ROOT_DIR}/rsshub"
RSSHUB_PID_FILE="${ROOT_DIR}/rsshub.pid"
RSSHUB_LOG_FILE="${LOG_DIR}/rsshub.log"
RSSHUB_MODE="${RSSHUB_MODE:-docker}"  # docker | node
RSSHUB_START_CMD="${RSSHUB_START_CMD:-pnpm dev}"

# Always run from project root so uvicorn can import the local `app` package.
cd "${ROOT_DIR}"

mkdir -p "${LOG_DIR}"

command_exists() {
    command -v "$1" >/dev/null 2>&1
}

docker_compose() {
    if docker compose version >/dev/null 2>&1; then
        docker compose "$@"
    elif command_exists docker-compose; then
        docker-compose "$@"
    else
        echo "❌ 未检测到 docker compose，请安装 Docker Compose v2 或 docker-compose"
        exit 1
    fi
}

start_postgres() {
    if ! command_exists docker; then
        echo "[postgres] ⚠️ 未检测到 docker，跳过 postgres 启动"
        return
    fi

    echo "[postgres] 启动 docker compose postgres ..."
    (cd "${ROOT_DIR}" && docker_compose up -d postgres)
}

start_api() {
    if [[ -f "${PID_FILE}" ]] && kill -0 "$(cat "${PID_FILE}")" >/dev/null 2>&1; then
        pid="$(cat "${PID_FILE}")"
        echo "[api] 已在运行 (pid ${pid})"
        return
    fi

    if [[ -x "${ROOT_DIR}/.venv/bin/uvicorn" ]]; then
        UVICORN_BIN="${ROOT_DIR}/.venv/bin/uvicorn"
    elif command_exists uvicorn; then
        UVICORN_BIN="$(command -v uvicorn)"
    else
        echo "[api] ❌ 未找到 uvicorn，请先在虚拟环境中安装依赖"
        exit 1
    fi

    echo "[api] 后台启动 FastAPI 服务 ..."
    nohup "${UVICORN_BIN}" app.main:app --host 0.0.0.0 --port 8080 \
        > "${LOG_FILE}" 2>&1 &
    echo $! > "${PID_FILE}"
    echo "[api] 已启动，PID=$(cat "${PID_FILE}")，日志写入 ${LOG_FILE}"
}

start_rsshub() {
    if [[ "${RSSHUB_MODE}" == "docker" ]]; then
        if ! command_exists docker; then
            echo "[rsshub] ❌ 未检测到 docker，无法启动 RSSHub (docker 模式)"
            exit 1
        fi
        echo "[rsshub] (docker) 启动 RSSHub 及依赖 ..."
        (cd "${ROOT_DIR}" && docker_compose up -d redis browserless rsshub)
        return
    fi

    if [[ -f "${RSSHUB_PID_FILE}" ]] && kill -0 "$(cat "${RSSHUB_PID_FILE}")" >/dev/null 2>&1; then
        pid="$(cat "${RSSHUB_PID_FILE}")"
        echo "[rsshub] (node) 已在运行 (pid ${pid})"
        return
    fi

    if ! command_exists pnpm; then
        echo "[rsshub] ❌ 未检测到 pnpm，请安装后重试 (node 模式)"
        exit 1
    fi

    echo "[rsshub] (node) 启动 RSSHub ..."
    echo "[rsshub] (node) 命令: ${RSSHUB_START_CMD}"
    if command_exists docker; then
        echo "[rsshub] (node) 先启动依赖 redis / browserless ..."
        (cd "${ROOT_DIR}" && docker_compose up -d redis browserless)
    else
        echo "[rsshub] (node) ⚠️ 未检测到 docker，需自行确保 redis 与 browserless 可用"
    fi
    (
        cd "${RSSHUB_DIR}"
        if [[ ! -d node_modules ]]; then
            echo "[rsshub] (node) 安装依赖 ..."
            pnpm install
        fi
        nohup bash -lc "${RSSHUB_START_CMD}" > "${RSSHUB_LOG_FILE}" 2>&1 &
        echo $! > "${RSSHUB_PID_FILE}"
    )
    echo "[rsshub] (node) 已启动，PID=$(cat "${RSSHUB_PID_FILE}"), 日志 ${RSSHUB_LOG_FILE}"
}

main() {
    start_postgres
    start_api
    start_rsshub
    echo "✅ 所有服务启动完毕"
}

main "$@"
